package com.daikit.daikit4gxt.client.utils.miscs;

import com.daikit.commons.shared.miscs.Couple;
import com.sencha.gxt.data.shared.TreeStore;


/**
 * Class giving methods to provide custom behavior for adding models to treestore after save or update. For example to
 * calculate the new parent model and index within parent of the saved item or to provide possibility to add children to
 * the modelToAdd.
 *
 * @author tcaselli
 * @version $Revision$ Last modifier: $Author$ Last commit: $Date$
 * @param <T>
 * @see #getNewParentModelAndIndexAfterSave(TreeStore, Object, int, Object)
 * @see #addModelToTreeStore(TreeStore, Object, int, Object)
 */
public class TreeStoreModifierCallback<T>
{
	/**
	 * Override this method to calculate the new parent model and index within parent of the saved item (in case of a
	 * {@link TreeStore} ). By default this method returns the former parent model and former index. The saved item will
	 * be removed from former parent and added to the new one.
	 *
	 * @param treeStore
	 *           the {@link TreeStore} in which the model has to be added updated save
	 * @param modelIndexInFormerParentModel
	 *           the index of the model within the former parent model
	 * @param formerParentModel
	 *           the former parent model of savedModel
	 * @param savedModel
	 *           the just saved model
	 * @return a {@link Couple} in which first is the new parent model and second is the model index within former parent
	 *         model
	 */
	public Couple<T, Integer> getNewParentModelAndIndexAfterSave(final TreeStore<T> treeStore, final T formerParentModel,
			final int modelIndexInFormerParentModel, final T savedModel)
	{
		return new Couple<T, Integer>(formerParentModel, modelIndexInFormerParentModel);
	}

	/**
	 * Method to be overridden to provide possibility to add children of the modelToAdd
	 *
	 * @param treeStore
	 *           the {@link TreeStore}
	 * @param parentModel
	 *           the former parent model (may be the same or may have changed during edition)
	 * @param modelIndexInFormerParentModel
	 *           the index where to add the model within the former parentModel (if -1 the add to the end) (not relevant
	 *           if parent model has changed during update)
	 * @param modelToAdd
	 *           the model to add
	 */
	public void addModelToTreeStore(final TreeStore<T> treeStore, final T parentModel, final int modelIndexInFormerParentModel, final T modelToAdd)
	{
		if (parentModel == null)
		{
			treeStore.add(modelToAdd);
		}
		else
		{
			if (modelIndexInFormerParentModel != -1)
			{
				treeStore.insert(parentModel, modelIndexInFormerParentModel, modelToAdd);
			}
			else
			{
				treeStore.add(parentModel, modelToAdd);
			}
		}
	}
}
